/**
 * 编辑作者：张诗涛
 * 创建时间：2018年5月5日 22点02分
 * 功能分类：爬虫数据业务逻辑
 */
import * as mysql from "mysql";
import { BaseLogic } from './baseLogic';
import { ReptileArticleEntity } from "../entitys/entity";
import { Config } from '../config';

interface IGetArticleList {
    pageIndex: number;
    pageSize: number;
}
interface IAddNewsData {
    title: string;
    content: string;
    guid: string;
    date: Date;
}
class ReptileLogic extends BaseLogic {
    constructor() {
        super();
    }

    getArticleList(params: IGetArticleList, callback: (list: ReptileArticleEntity[]) => void) {
        let connection = super.requestConnect("reptile_db");

        params.pageSize = parseInt(<any>params.pageSize) || 10;
        params.pageIndex = parseInt(<any>params.pageIndex) || 1;

        let startAt: number = params.pageSize * params.pageIndex - params.pageSize;
        let maxItems: number = params.pageSize;

        let sql = `SELECT * FROM article ORDER BY date DESC LIMIT ${startAt}, ${maxItems}`;

        return connection.dataRows<ReptileArticleEntity>(sql, (list) => {

            callback(list);

        });
    }

    addArticleData(params: IAddNewsData, callback: (data: { msg: string, success: boolean }) => void) {

        let ret = { msg: "参数类型错误", success: false };

        // valid
        if (params && undefined != params.content && undefined != params.date && undefined != params.guid && undefined != params.title) {

            let connection = super.requestConnect("reptile_db");

            let sql = `INSERT INTO article (title, content, date, guid) VALUES (${mysql.escape(params.title)},${mysql.escape(params.content)},${mysql.escape(params.date)},${mysql.escape(params.guid)})`;

            return connection.affectedRows(sql, (affectedRows) => {

                if (affectedRows) {

                    ret.msg = "添加成功";
                    ret.success = true;

                } else {
                    ret.msg = "添加失败:";
                }

                callback(ret);
            });

        } else {
            callback(ret);
        }

    }

    hasArticleData(guid: string, callback: (data: { msg: string, success: boolean, total: number }) => void) {
        
        guid = decodeURIComponent(guid);

        let ret = { msg: "参数类型错误", success: false, total: 0 };

        // valid
        if (undefined != guid) {

            let connection = super.requestConnect("reptile_db");

            let sql = `SELECT * FROM ARTICLE WHERE guid=${mysql.escape(guid)}`;

            return connection.dataRows(sql, (list) => {

                ret.success = true;

                if (!list.length) {

                    ret.msg = "查询成功";

                } else {
                    ret.msg = "数据已存在";
                    ret.total = list.length;
                }

                callback(ret);
            });

        } else {
            callback(ret);
        }

    }
}

export { ReptileLogic }